import Promise from 'promise';
import validator from 'validator';
import * as ResultMsg from '../constrants/ResultMsg';
import { errorJson, successJson } from '../common/response';
import { checkId, checkDoc, checkDocs } from '../common/check';
import { StaticProxy } from '../proxy';

export {
  list,
  data,
  add,
  del,
  update,
};

async function list(req, res, next) {
  const appId = res.locals.appId;

  try {
    let docs = await StaticProxy.find(appId, {}, {});
    successJson(req, res, {data: docs})
  } catch(err) {
    next(err);
  }
}

async function data(req, res, next) {
  const appId = res.locals.appId;
  const id = req.params.sid;

  try {
    let doc = await StaticProxy.findOneById(appId, {_id: id}, {});
    successJson(req, res, {data: doc})
  } catch(err) {
    next(err);
  }
}

async function add(req, res, next) {
  const appId = res.locals.appId;
  const name = req.body.name;
  const title  = req.body.title;
  const content = req.body.content;
  const isHtml = req.body.isHtml || false;
  const isContrast = req.body.isContrast || false;

  try {
    let doc = await StaticProxy.findOneByName(appId, name);
    if (doc) {
      return errorJson(req, res, {err: ResultMsg.REPEAT_DATA})
    }

    let data = {
      name,
      title,
      content,
      isHtml,
      isContrast
    };

    await StaticProxy.create(appId, data);
    successJson(req, res, {msg: ResultMsg.CREATE_SUCCESS, url: '/static/' + name + '/show?appId=' + appId});
  } catch(err) {
    next(err);
  }
}

async function update(req, res, next) {
  const appId = res.locals.appId;
  const id = req.params.sid;
  const name = req.body.name;
  const title  = req.body.title;
  const content = req.body.content;
  const isHtml = req.body.isHtml || false;
  const isContrast = req.body.isContrast || false;

  try {
    let doc = await StaticProxy.findOneById(appId, id);
    if (!doc) return errorJson(req, res, {err: ResultMsg.DATA_NOT_FOUND});

    let data = {
      name,
      title,
      content,
      isHtml,
      isContrast
    };

    await StaticProxy.update(appId, id, data);
    successJson(req, res, {msg: ResultMsg.UPDATE_SUCCESS, url: '/static/' + name + '/show?appId=' + appId});
  } catch(err) {
    next(err);
  }
}

async function del(req, res, next) {
  const appId = res.locals.appId;
  const id = req.params.sid;

  try {
    await StaticProxy.remove(appId, {_id: id});
    successJson(req, res, {msg: ResultMsg.DELETED_SUCCESS});
  } catch(err) {
    next(err);
  }
}
